﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DIWAGIS.Modules;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Editor;
using ESRI.ArcGIS.EditorExt;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.GlobeCore;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using DIWAGIS.ApplicationLayer.BanDo;
using DIWAGIS.Class;

namespace DIWAGIS.ApplicationLayer.BanDo
{
    public sealed partial class frmIndentifyFeature : Form, ICommand, ITool
    {
        #region Class Private Member
        IHookHelper m_hookHelper = null;
        Bitmap m_Bitmap;
        string m_Caption;
        private System.Windows.Forms.Cursor m_Cursor;
        bool m_Checked;
        IMap m_Map;
        #endregion

        #region Class Private Method
        #endregion

        #region Class Constructor

        public frmIndentifyFeature()
        {
            InitializeComponent();
            m_Checked = false;
            m_Caption = "Identify Feature Tool - nhận dạng đối tượng";
            //System.Drawing.Image m_Image = Image.FromFile("IdentifyFeatureTool.bmp");
            //m_Bitmap = new System.Drawing.Bitmap(GetType(), "IdentifyFeatureTool.bmp");
            //IntPtr m = m_Bitmap.GetHbitmap();
            //m_Cursor = new System.Windows.Forms.Cursor(GetType(), GetType().Name + ".cur");//new System.Windows.Forms.Cursor("C:/DIWAGISProject/diwagisproject/DIWAGIS/ApplicationLayer/BanDo/IdentifyFeatureTool.cur");

        }
        #endregion

        #region ICommand Members

        public int Bitmap
        {
            get { return (Convert.ToInt32(m_Bitmap.GetHbitmap())); }
        }

        public string Caption
        {
            get { return m_Caption; }
        }

        public string Category
        {
            get { throw new NotImplementedException(); }
        }

        public bool Checked
        {
            get { return m_Checked; }
        }

        public int HelpContextID
        {
            get { throw new NotImplementedException(); }
        }

        public string HelpFile
        {
            get { throw new NotImplementedException(); }
        }

        public string Message
        {
            get { throw new NotImplementedException(); }
        }

        public void OnClick()
        {

        }

        public void OnCreate(object Hook)
        {
            if (Hook != null)
            {
                m_hookHelper = new HookHelperClass();
                m_hookHelper.Hook = Hook;
            }
        }

        public string Tooltip
        {
            get { throw new NotImplementedException(); }
        }

        #endregion

        #region ITool Members

        public int Cursor
        {
            get { return m_Cursor.Handle.ToInt32(); }
        }

        public new bool Deactivate()
        {
            throw new NotImplementedException();
        }

        public bool OnContextMenu(int x, int y)
        {
            throw new NotImplementedException();
        }

        public void OnDblClick()
        {
            //throw new NotImplementedException();
        }

        public void OnKeyDown(int keyCode, int shift)
        {
            //throw new NotImplementedException();
        }

        public void OnKeyUp(int keyCode, int shift)
        {
            //throw new NotImplementedException();
        }

        public void OnMouseDown(int button, int shift, int x, int y)
        {

            if (m_hookHelper == null)
            {
                return;
            }
            try
            {
                if (button == 1)
                {
                    m_Map = m_hookHelper.FocusMap;
                    IPoint m_Point = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
                    if (cboBoxLayer.Items.Count == 0 || cboBoxLayer.SelectedItem == null)
                    {
                        MessageBox.Show("Chưa chọn lớp đối tượng hoặc chưa có dữ liệu load vào bản đồ!");
                        return;
                    }
                    else
                    {
                        //Get the Layer that matched the name in the cboLayer
                        if (m_Map.LayerCount == 0) return;
                        ILayer m_Layer = null;
                        //ICompositeLayer m_Compositelayer = m_hookHelper.FocusMap.get_Layer(0) as ICompositeLayer;

                        for (int i = 0; i < generalVariable.mapControl.LayerCount; i++)
                        {
                            if (generalVariable.mapControl.get_Layer(i).Name == cboBoxLayer.SelectedItem.ToString())
                            {
                                m_Layer = generalVariable.mapControl.get_Layer(i);
                                break;
                            }
                        }
                        IFeatureClass m_FeatureClass = (m_Layer as IFeatureLayer).FeatureClass;

                        //
                        IRubberBand m_RubberBand = new RubberEnvelopeClass();
                        IGeometry m_Geometry = m_RubberBand.TrackNew(m_hookHelper.ActiveView.ScreenDisplay, null);

                        IArea area = (IArea)m_Geometry;
                        listBoxFeatures.Items.Clear();
                        dataGridViewProperties.Rows.Clear();
                        //Extra logic to cater for the situation where the user simply clicks a point on the map 
                        //or where envelope is so small area is zero 
                        if ((m_Geometry.IsEmpty) || (area.Area == 0))
                        {

                            //create a new envelope 
                            IEnvelope tempEnv = new EnvelopeClass();

                            //create a small rectangle 
                            ESRI.ArcGIS.esriSystem.tagRECT RECT = new tagRECT();
                            RECT.bottom = 0;
                            RECT.left = 0;
                            RECT.right = 15;
                            RECT.top = 15;

                            //transform rectangle into map units and apply to the tempEnv envelope 
                            IDisplayTransformation dispTrans = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation;
                            dispTrans.TransformRect(tempEnv, ref RECT, 4); //4 = esriDisplayTransformationEnum.esriTransformToMap)
                            tempEnv.CenterAt(m_Point);
                            m_Geometry = (IGeometry)tempEnv;
                        }

                        listBoxFeatures.Items.Clear();

                        //Spatial filter for specific layer on cboLayer
                        ISpatialFilter m_SpatialFilter = new SpatialFilterClass();
                        m_SpatialFilter.Geometry = m_Geometry;
                        m_SpatialFilter.GeometryField = m_FeatureClass.ShapeFieldName;
                        m_SpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                        m_SpatialFilter.SubFields = "";
                        m_SpatialFilter.WhereClause = "";



                        IQueryFilter m_QueryFilter = m_SpatialFilter as IQueryFilter;
                        IFeatureCursor m_FeatureCursor = m_FeatureClass.Search(m_QueryFilter, true);
                        IFeature m_Feature = m_FeatureCursor.NextFeature();
                        IArray m_Array = new ArrayClass();
                        while (m_Feature != null)
                        {
                            m_Array.Add(m_Feature.Shape);
                            String ObjectID_Field = m_Feature.get_Value(0).ToString();
                            listBoxFeatures.Items.Add(ObjectID_Field);
                            m_Feature = m_FeatureCursor.NextFeature();
                        }
                        if (listBoxFeatures.Items.Count != 0)
                        {
                            listBoxFeatures.SelectedIndex = 0;
                        }
                        toolStripStatusLabelSoLuongDoiTuong.Text = "Số lượng đối tượng: " + m_Array.Count.ToString();
                        //Hiện lại form nếu form bị ẩn và có hơn một đối tượng được chọn
                        if (!this.Visible && m_Array.Count != 0)
                        {
                            this.Visible = true;
                            if (this.WindowState == FormWindowState.Minimized)
                            {
                                this.WindowState = FormWindowState.Normal;
                            }
                            this.Show();
                        }
                        ////Flash Feature
                        //IHookActions m_HookActions = m_hookHelper as IHookActions;
                        //if (m_HookActions.get_ActionSupportedOnMultiple(m_Array,esriHookActions.esriHookActionsFlash))
                        //    m_HookActions.DoActionOnMultiple(m_Array, esriHookActions.esriHookActionsFlash);


                    }
                }

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
                //throw;
            }

        }

        public void OnMouseMove(int button, int shift, int x, int y)
        {
            //throw new NotImplementedException();
        }

        public void OnMouseUp(int button, int shift, int x, int y)
        {
            //throw new NotImplementedException();
        }

        public void Refresh(int hdc)
        {
            //throw new NotImplementedException();
        }

        #endregion ITool Members

        private void buttonStartEditing_Click(object sender, EventArgs e)
        {
            buttonStartEditing.Enabled = false;
            dataGridViewProperties.ReadOnly = false;
            buttonUpdate.Enabled = true;
            buttonStopEditing.Enabled = true;
        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            //Lưu thay đổi xuống CSDL
            buttonUpdate.Enabled = false;
            buttonStartEditing.Enabled = true;
        }

        private void buttonStopEditing_Click(object sender, EventArgs e)
        {
            DialogResult m_DR = MessageBox.Show("Bạn có muốn lưu thay đổi?", "Lưu thay đổi", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            switch (m_DR)
            {
                //Không lưu thay đổi và không ngừng chỉnh sửa
                case DialogResult.Cancel:
                    break;

                //Ngừng chỉnh sửa và không lưu thay đổi
                case DialogResult.No:
                    dataGridViewProperties.ReadOnly = true;
                    buttonStartEditing.Enabled = true;
                    buttonUpdate.Enabled = false;
                    buttonStartEditing.Enabled = false;
                    break;

                //Ngừng chỉnh sửa và lưu thay đổi
                case DialogResult.Yes:
                    dataGridViewProperties.ReadOnly = true;
                    buttonStartEditing.Enabled = true;
                    buttonUpdate.Enabled = false;
                    buttonStopEditing.Enabled = false;
                    break;
                default:
                    break;
            }
        }

        private void cboBoxLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBoxFeatures.Items.Clear();
            dataGridViewProperties.Rows.Clear();
        }

        private void listBoxFeatures_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Clear the DatagridView
            dataGridViewProperties.Rows.Clear();
            //Get the Layer that matched the name in the cboLayer
            if (m_Map.LayerCount == 0) return;
            ILayer m_Layer = null;
            IHookActions m_HookActions;
            //ICompositeLayer m_Compositelayer = m_hookHelper.FocusMap.get_Layer(0) as ICompositeLayer;
            for (int i = 0; i < generalVariable.mapControl.LayerCount; i++)
            {
                if (generalVariable.mapControl.get_Layer(i).Name == cboBoxLayer.SelectedItem.ToString())
                {
                    m_Layer = generalVariable.mapControl.get_Layer(i);
                    break;
                }
            }

            ITable m_Table = (m_Layer as IFeatureLayer) as ITable;
            //Get the row that correspond to Selectet OID in Listbox
            IRow m_Row = m_Table.GetRow(Convert.ToInt32(listBoxFeatures.SelectedItem));

            string m_FieldName;
            ICodedValueDomain cvDomain = null;
            for (int i = 0; i < m_Table.Fields.FieldCount; i++)
            {
                cvDomain = m_Table.Fields.get_Field(i).Domain as ICodedValueDomain;
                m_FieldName = m_Table.Fields.get_Field(i).Name;
                if (m_FieldName.ToUpper() == "OBJECTID" || m_FieldName.ToUpper() == "SHAPE" || m_FieldName.ToUpper() == "SHAPE_LENGTH")
                {

                }
                else
                {
                    string value = m_Row.get_Value(i).ToString();
                    if ((null != cvDomain))
                    {
                        DataGridViewTextBoxCell m_DataGridViewTextBoxCell = new DataGridViewTextBoxCell();
                        m_DataGridViewTextBoxCell.Value = m_Table.Fields.get_Field(i).AliasName;
                        DataGridViewComboBoxCell m_DataGridViewComboBoxCell = new DataGridViewComboBoxCell();
                        m_DataGridViewComboBoxCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                        // Tạo list Item cho CboBox
                        for (int i2 = 0; i2 < cvDomain.CodeCount; i2++)
                        {
                            m_DataGridViewComboBoxCell.Items.Add(cvDomain.get_Name(i2));
                        }

                        for (int valueCount = 0; valueCount < cvDomain.CodeCount; valueCount++)
                        {
                            if (value == Convert.ToString(cvDomain.get_Value(valueCount)))
                            {
                                value = cvDomain.get_Name(valueCount);
                                break;
                            }
                        }
                        m_DataGridViewComboBoxCell.Value = value;
                        DataGridViewRow m_DataGridViewRow = new DataGridViewRow();
                        m_DataGridViewRow.Cells.Add(m_DataGridViewTextBoxCell);
                        m_DataGridViewRow.Cells.Add(m_DataGridViewComboBoxCell);
                        dataGridViewProperties.Rows.Add(m_DataGridViewRow);

                    }
                    else
                    {
                        dataGridViewProperties.Rows.Add(m_Table.Fields.get_Field(i).AliasName, value);
                    }

                }
            }
            //Flash the feature
            IGeometry m_Geometry = (m_Row as IFeature).Shape;
            m_HookActions = m_hookHelper as IHookActions;
            m_HookActions.DoAction(m_Geometry, esriHookActions.esriHookActionsFlash);
        }

        private void cboBoxLayer_Click(object sender, EventArgs e)
        {
            if (m_hookHelper == null) return;
            {
                object m_hold = cboBoxLayer.SelectedItem;
                cboBoxLayer.Items.Clear();
                if (m_hookHelper.FocusMap.LayerCount > 0)
                {
                    //ICompositeLayer m_Compositelayer = m_hookHelper.FocusMap.get_Layer(0) as ICompositeLayer;
                    for (int i = 0; i < generalVariable.mapControl.LayerCount; i++)
                    {
                        cboBoxLayer.Items.Add(generalVariable.mapControl.get_Layer(i).Name);
                    }
                }
                cboBoxLayer.SelectedItem = m_hold;
            }
        }

        private void frmIndentifyFeature_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Visible = false;
            //this.Hide();
            e.Cancel = true;
        }

        private void frmIndentifyFeature_Load(object sender, EventArgs e)
        {
            buttonStartEditing.Enabled = true;
            buttonStopEditing.Enabled = false;
            buttonUpdate.Enabled = false;
        }

        private void frmIndentifyFeature_Shown(object sender, EventArgs e)
        {
            if (m_hookHelper == null) return;
            {
                cboBoxLayer.Items.Clear();
                if (m_hookHelper.FocusMap.LayerCount > 0)
                {
                    //ICompositeLayer m_Compositelayer = m_hookHelper.FocusMap.get_Layer(0) as ICompositeLayer;
                    for (int i = 0; i < generalVariable.mapControl.LayerCount; i++)
                    {
                        cboBoxLayer.Items.Add(generalVariable.mapControl.get_Layer(i).Name);
                    }
                    cboBoxLayer.SelectedIndex = 0;
                }
            }
        }
    }
}
